package cn.ssm.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import cn.ssm.util.Constans2;
import cn.ssm.pojo.User;
import cn.ssm.service.UserService;

/*
 * 登陆
 * @author Administrator
 *
 */
@Controller
@SessionAttributes
public class LoginController2 {
	@Autowired
	UserService userService;

	@RequestMapping("/getLoginUser.htm")
	@ResponseBody
	public Object getLoginUser(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);
		User user = (User) request.getSession().getAttribute(Constans2.LOGIN2_KEY);
		if (user != null) {
			map.put("result", user);
			map.put("message", "获取登录用户成功");
			map.put("success", true);
		}

		return map;

	}

	@RequestMapping("/login2.htm")
	@ResponseBody
	public Object login(@Param("userName") String userName, @Param("password") String password,
			HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);

		try {
			User user = userService.getUser(userName, password);
			if (user != null) {
				request.getSession().setAttribute(Constans2.LOGIN2_KEY, user);

				map.put("success", true);
				map.put("message", "存在此用户");
			} else {
				map.put("success", false);
				map.put("message", "用户不存在！");
			}
		} catch (Exception e) {
			map.put("message", "查询用户出错，请联系管理员");
			e.printStackTrace();
		}
		return map;
	}

	@RequestMapping("/userOut.htm")
	@ResponseBody
	public Object userOut(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);
		request.getSession().setAttribute(Constans2.LOGIN2_KEY, null);
		if (Constans2.LOGIN2_KEY == null) {
			map.put("message", "登出成功");
			map.put("success", true);
		}
		return map;
	}
}
